<template>
    <div class="box" v-if="showContent == 0">
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <span>学员考试</span>
                </div>
            </template>
            <!-- 表单查询部分 -->
            <div class="query">
                <el-form :inline="true" :model="formInline" class="demo-form-inline">
                    <el-row :gutter="20">
                        <el-col :span="7" :offset="0">
                            <el-form-item label="学员姓名：">
                                <el-input v-model="formInline.name" placeholder="请输入学员姓名" clearable />
                            </el-form-item>

                        </el-col>
                        <el-col :span="7" :offset="0">
                            <el-form-item label="手机号码：">
                                <el-input v-model="formInline.tel" placeholder="请输入学员手机号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" :offset="0">
                            <el-form-item label="身份证号：">
                                <el-input v-model="formInline.cardId" placeholder="请输入学员省份证号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :span="2" :offset="0">
                            <el-form-item>
                                <el-button type="warning" @click="onSubmit">查询</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="7" :offset="0">
                            <el-form-item label="报名校区：">
                                <el-select v-model="formInline.schoolName" placeholder="请选择报名校区" clearable>
                                    <el-option label="小象校区" value="小象校区" />
                                    <el-option label="汉丰驾校" value="汉丰驾校" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" :offset="0">
                            <el-form-item label="准驾车型：">
                                <el-select v-model="formInline.class" placeholder="请选择准驾车型" clearable>
                                    <el-option label="C1" value="C1" />
                                    <el-option label="A1" value="A1" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="7" :offset="0">
                            <el-form-item label="考试进度：">
                                <el-select v-model="formInline.subjectState" placeholder="请选择考试进度" clearable>
                                    <el-option label="考试通过" value="考试通过" />
                                    <el-option label="科目二就绪" value="科目二就绪" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="20">
                        <el-col :span="10" :offset="0">
                            <el-form-item label="进度时间：">
                                <el-date-picker v-model="formInline.progress" type="daterange" range-separator="~"
                                    start-placeholder="开始时间" end-placeholder="结束时间" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="10" :offset="0">
                            <el-form-item label="合格日期：">
                                <el-date-picker v-model="formInline.passTime" type="daterange" range-separator="~"
                                    start-placeholder="开始时间" end-placeholder="结束时间" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>

            </div>

            <!-- 表头筛选按钮 -->
            <div class="threeBtn">
                <el-row justify="space-between">
                    <el-col :span="16" :offset="0">
                        <el-button type="success" round :icon="Edit" @click="handleBatchSubject('科目二')">分配科二教练</el-button>
                        <el-button type="warning" round :icon="Edit" @click="handleBatchSubject('科目三')">分配科三教练</el-button>
                        <el-button type="danger" round :icon="Edit" @click="handleBatchState('批量修改进度')">批量修改进度</el-button>
                    </el-col>
                    <!-- 三个小按钮 -->
                    <el-col :span="3" :offset="0">
                        <el-tooltip content="导出" placement="top" effect="light">
                            <el-button type="success" :icon="Upload" circle @click="handleExportExcel" />
                        </el-tooltip>
                        <el-tooltip content="筛选列" placement="top" effect="light">
                            <el-button type="danger" :icon="Operation" circle />
                        </el-tooltip>
                        <el-tooltip content="打印" placement="top" effect="light">
                            <el-button type="warning" :icon="Printer" circle />
                        </el-tooltip>
                    </el-col>
                </el-row>

            </div>
            <!-- 表格部分 -->
            <!-- 表格文本居中对齐 -->
            <el-table :data="tableData" style="width: 100%" border
                :header-cell-style="{ background: '#f2f2f2', textAlign: 'center' }" :cell-style="{ textAlign: 'center' }"
                @selection-change="selChange">
                <el-table-column type="selection" width="55" />
                <el-table-column fixed prop="name" label="学员姓名" width="100" />
                <el-table-column prop="cardId" label="身份证号" width="200" />
                <el-table-column prop="tel" label="手机号码" width="140" />
                <el-table-column prop="carType" label="准驾车型" width="120" />
                <el-table-column prop="subject" label="当前科目" width="120" />
                <el-table-column prop="subjectState" label="当前进度" width="120" />
                <el-table-column prop="progressTime" label="进度时间" width="120" />
                <el-table-column prop="count" label="考试次数" width="120" />
                <el-table-column prop="passTime" label="合格时间" width="120" />
                <el-table-column prop="coach" label="分配教练" width="120" />
                <el-table-column prop="schoolName" label="校区" width="120">
                    <!-- 接收表格行数据 -->
                    <template #default="scope">
                        {{ schoolnameMap[scope.row.schoolName] }}
                    </template>
                </el-table-column>
                <el-table-column prop="referrer" label="推荐人" width="120" />
                <el-table-column prop="comment" label="备注" width="120" />
                <el-table-column fixed="right" label="操作" width="200">
                    <template #default="scope">
                        <el-button class="mr2" type="success" plain round size="small" :icon="Edit"
                            @click="handleProgress(scope)">设置进度</el-button>
                        <el-dropdown>
                            <el-button type="warning" plain round size="small" :icon="MoreFilled"
                                @click="showClick">更多</el-button>
                            <template #dropdown>
                                <el-dropdown-menu size="small">
                                    <el-dropdown-item :icon="User"
                                        @click="handlePushDetail(scope.row)">学员详情</el-dropdown-item>
                                    <el-dropdown-item :icon="Reading"
                                        @click="handlePush('/exam/preExam',scope.row.cardId)">预考记录</el-dropdown-item>
                                    <el-dropdown-item :icon="Edit"
                                        @click="handlePush('/exam/mockExam',scope.row.cardId)">模拟考</el-dropdown-item>
                                    <el-dropdown-item :icon="Orange"
                                        @click="handleAssignCoach(scope.row)">分配教练</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>

                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页部分 -->
            <!-- 分页器汉化 -->
            <el-config-provider :locale="locale">
                <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
                    :small="small" :disabled="disabled" :background="background"
                    layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </el-config-provider>
            <!-- 设置进度对话框 -->
            <el-dialog v-model="centerDialogVisible" width="30%" align-center title="更新考试进度">
                <!-- v-if:解决数据不更新的问题,子组件没有销毁,导致页面只渲染一次 -->
                <ModyProgress v-if="centerDialogVisible" :rowData="rowData" @getisShow="handleDialog" />
            </el-dialog>
            <!-- 分配教练对话框 -->
            <el-dialog v-model="AssignVisible" width="30%" align-center :title="title">
                <AssignTeacher v-if="AssignVisible" :assignRowData="assignRowData" @assignIsShow="handleAssinDialog"
                    :schoolnameMap="schoolnameMap" :showname="showname" />
            </el-dialog>

            <!-- 批量分配教练 -->
            <el-drawer v-model="drawer" :title="drawerTitle">
                <ExamBatchForm v-if="drawer && drawerTitle.indexOf('修改') != -1" :selArr="idsArr" :tableData="tableData"
                    @getNewTableDate="handleTableData" :formdata="formdata" :currentsubject="currentSubject" />
                <AssignTeacher v-else-if="drawer" @assignIsShow="handleAssinDialog" :schoolnameMap="schoolnameMap"
                    :showname="showname" :selArr="idsArr" :conditionData="conditionData" :tableData="tableData" />
            </el-drawer>
        </el-card>
    </div>
    <div v-else-if="showContent == 1">
        <stuDetail />
    </div>
    <div v-else-if="showContent == 2">预考记录</div>
    <div v-else-if="showContent == 3">模拟考</div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { reactive } from 'vue'
import { stuExamInfoGet } from '../../api/student'
import { Edit, MoreFilled, Upload, Printer, Operation, User, Reading, Orange } from '@element-plus/icons-vue'
//分页器汉化
import { ElConfigProvider, ElMessage } from 'element-plus';
import locale from "element-plus/es/locale/lang/zh-cn";
import { exportExcel } from "../../utils/exportExcel"
import { examType, objType } from "../../types/examType"
import ModyProgress from './components/modyProgress.vue'
import type { DropdownInstance } from 'element-plus'
import AssignTeacher from './components/assignTeacher.vue';
import { getSchoolName } from "../../utils/schoolName"
import ExamBatchForm from "./components/eaxmbatchForm.vue"
import { useRouter } from "vue-router"

// import moment from 'moment' 
//获取校区名称id-name
const router = useRouter()
let showname = ref(0)
let schoolnameMap = reactive<objType>({
    objectid: ''
})
schoolnameMap = await getSchoolName()
//子页面跳转
const showContent = ref(0)
//表单数据
const formInline = reactive({
    name: '',
    cardId: '',
    schoolName: '',
    class: '',
    subjectState: '',
    tel: '',
    progress: [],
    passTime: []
})
const tableData = ref<Array<examType>>([])
//表单查询功能
const onSubmit = () => {
    stuExamInfoGet(1, 5, { ...formInline }).then(res => {
        tableData.value = res.data.results
        total.value = res.data.count
    })
}
//获取学员数据

stuExamInfoGet(1, 5).then(async (res) => {
    tableData.value = res.data.results
    total.value = res.data.count
})
// 分页功能
//当前页码
const currentPage = ref(1)
// 每页显示条数
const pageSize = ref(5)
const total = ref(100)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)
const handleSizeChange = (val: number) => {
    pageSize.value = val
    currentPage.value = 1
    stuExamInfoGet(currentPage.value, val, { ...formInline }).then(res => {
        tableData.value = res.data.results
        total.value = res.data.count
    })
}
const handleCurrentChange = (val: number) => {
    currentPage.value = val
    stuExamInfoGet(val, pageSize.value, { ...formInline }).then(res => {
        // console.log(res);
        tableData.value = res.data.results
        total.value = res.data.count
    })
}

//表格导出功能
const handleExportExcel = () => {
    console.log("表格导出");
    //表头中文名
    const titleArr = ['id', '巡河次数', '完成次数', '巡河人员', '时间']
    exportExcel(tableData.value, 'test', titleArr, 'sheetName');
}

//设置进度
const centerDialogVisible = ref(false)
let rowData = reactive({
    objectId: '',
    name: '',
    subject: '',
    progress: '',
    progressTime: '',
    cardId: '',
    tel: '',
    class: '',
    comment: '',
    subjectState: '',
    referrer: '',
    count: '',
    passTime: '',
    coach: '',
    schoolName: '',
    carType: '',
    state: '',
    completeTime: '',
})
const handleProgress = (val: any) => {
    rowData = val.row
    centerDialogVisible.value = true
}

//子父通信，关闭对话框
const handleDialog = () => {
    centerDialogVisible.value = false
}
// 更多菜单
const dropdown1 = ref<DropdownInstance>()
function showClick() {
    if (!dropdown1.value) return
    dropdown1.value.handleOpen()
}
//学员详情跳转
const handlePushDetail = (row: any) => {
    router.push({
        path: `/students/details`,
        query: {
            objectId: row.objectId,
            cardId:row.cardId
        }
    })
}
//跳转其他菜单
const handlePush = (path: string,cardId:string) => {
    console.log(cardId);
    router.push({
        path,
        query:{
            cardId,
        }
    })
}
//个人分配教练
const AssignVisible = ref(false)
const title = ref("")
let assignRowData = reactive({}) as examType
const handleAssignCoach = (row: examType) => {
    if (row.subjectState == "科目二就绪") {
        AssignVisible.value = true
        showname.value = 1
        title.value = "分配科目二教练"
        assignRowData = row
    } else if (row.subjectState == "科目三就绪") {
        AssignVisible.value = true
        showname.value = 1
        title.value = "分配科目三教练"
        assignRowData = row
    } else {
        ElMessage.error("当前科目不能分配教练")
    }
}
//关闭个人分配教练
const handleAssinDialog = (coach: string) => {
    AssignVisible.value = false
    drawer.value = false
    if (idsArr.value.length) {
        idsArr.value.forEach(id => {
            console.log("打印选中id", id);
            tableData.value.forEach(item => {
                if (item.objectId == id) {
                    item.coach = coach
                }
            })
        })
    }
}
//批量修改
let formdata = reactive({})
let selsArr = ref<examType[]>([])  //选中行数据
let idsArr = ref<Array<string>>([])   //所选择的学员id数组
let currentSubject = ref('')
const selChange = (sel: examType[]) => {
    selsArr.value = sel
}
//批量分配教练功能
const drawer = ref(false)
interface ConditionDataType {
    carType: string;
    coach: string;
    object: string
    schoolName: string
}
let conditionData = ref<ConditionDataType>({} as ConditionDataType)
const drawerTitle = ref('')
const handleBatchSubject = (val: string) => {
    let sels = selsArr.value
    if (sels.length) {
        let csubject = val
        let ccarType = sels[0].carType
        let cschoolName = sels[0].schoolName
        let subjectState = 1
        let stat = 1
        sels.map(item => {
            if (item.subject != csubject || item.carType != ccarType || item.schoolName != cschoolName || item.subjectState.indexOf("就绪") == -1) {
                stat = 0
                subjectState = 0
            }
        });
        if (stat && subjectState) {
            //解构赋值会让响应式数据失去响应性
            conditionData.value = { object: csubject, carType: ccarType, schoolName: schoolnameMap[cschoolName], coach: "" }
            let idArr: Array<string> = []
            sels.forEach(item => {
                idArr.push(item.objectId)
            });
            idsArr.value = idArr
            currentSubject.value = csubject
            drawer.value = true
            showname.value = 0
            drawerTitle.value = `批量分配${val}教练`
        } else {
            ElMessage({
                message: `必须选择同一校区的同一车型，且当前科目为${val}并且是就绪状态的学员`,
                type: 'warning',
            })
        }
    } else {
        ElMessage({
            message: '至少选择一条数据',
            type: 'warning',
        })
    }
}
//点击批量修改时触发事件
const handleBatchState = (title: string) => {
    let sels = selsArr.value
    if (sels.length) {
        let csubject = sels[0].subject
        let csubjectState = sels[0].subjectState
        let cschoolName = sels[0].schoolName
        let stat = 1
        sels.map(item => {
            if (item.subject != csubject || item.subjectState != csubjectState || item.schoolName != cschoolName) {
                stat = 0
            }
        });
        if (stat) {
            let idArr: Array<string> = []
            sels.forEach(item => {
                idArr.push(item.objectId)
            });
            idsArr.value = idArr
            currentSubject.value = csubject
            drawer.value = true
            drawerTitle.value = title
        } else {
            ElMessage({
                message: '必须选择同一校区的同一车型的相同科目',
                type: 'warning',
            })

        }
    } else {
        ElMessage({
            message: '至少选择一条数据',
            type: 'warning',
        })
    }
}
const handleTableData = (nval: examType[]) => {
    drawer.value = false
    // 接收到的值
    tableData.value = nval
}
</script>
<style lang="scss" scoped>
.query {
    border: 1px solid #ddd;
    padding: 20px;
}

.el-pagination {
    margin-top: 20px;
}

.threeBtn {
    border: 1px solid #ddd;
    background: #f2f2f2;
    margin-top: 20px;
    padding: 16px;
}
</style>